package cn.com.xinjinfu.pdoulcProduct.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.WebView.YaoqingWeb;
import cn.com.xinjinfu.pdoulcProduct.activity.login.CheckMobileActivity;
import cn.com.xinjinfu.pdoulcProduct.adapter.ImagePagerAdapter;
import cn.com.xinjinfu.pdoulcProduct.common.ConstantValues;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.entity.HomeBean;
import cn.com.xinjinfu.pdoulcProduct.entity.HomeBean.BannerList;
import cn.com.xinjinfu.pdoulcProduct.entity.User;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.JSONManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.ToastManager;
import cn.com.xinjinfu.pdoulcProduct.activity.user.QianDaoAct;
import cn.com.xinjinfu.pdoulcProduct.manager.UIManager;
import cn.com.xinjinfu.pdoulcProduct.utils.CommonUtils;
import cn.com.xinjinfu.pdoulcProduct.adapter.FragmentViewPagerAdapter;
import cn.com.xinjinfu.pdoulcProduct.utils.NewUtil;
import cn.com.xinjinfu.pdoulcProduct.utils.SharedPreferencesUtils;
import cn.com.xinjinfu.pdoulcProduct.view.ScrollableLinearLayout;
import cn.com.xinjinfu.pdoulcProduct.view.bannerview.CircleFlowIndicator;
import cn.com.xinjinfu.pdoulcProduct.view.bannerview.ViewFlow;

/**
 * 我要理财
 * Created by android-adt on 2015/12/29.
 */
public class HomeFragment extends BaseFragment implements ScrollableLinearLayout.OnScrollYChangeListener
        , View.OnClickListener {
    private ScrollableLinearLayout mainContainer;
    private Dialog dg;
    private View topbar_background;
    /**
     * 上标头总资产 的高度
     */
    public static final int ENTRANCE_GRIDVIEW_HEIGHT = 170;
//    public static final int ENTRANCE_GRIDVIEW_HEIGHT = 250;

    /**
     * 承载项目Fragment的主viewpager
     */
    private ViewPager mViewPager;
    private ImageView hongbao,top_qiandao_icon;
    private FragmentViewPagerAdapter mAdapter;

    public static final String TAG = "HomeFragment";
    private RequestQueue requen;
    private Activity mActivity;
    private LinearLayout top_qiandao,  ll_blell_title1, ll_blell_title2;
    private RelativeLayout tv_anyone_transfer,tv_my_newproject;
    private HomeBean homeBean;
    private TextView tv_title;

    private AnimationDrawable mAnimation;
    private ViewFlow mViewFlow;
    private CircleFlowIndicator  mFlowIndicator;
    private ArrayList<BannerList> bannerList;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.mActivity = activity;
    }

    @Override
    protected void lazyLoad() {
    }

    //加载首页fragment
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_home, container, false);
        initView(view);
        initOnChangeListener();
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        requen = Volley.newRequestQueue(mActivity);
        initData();
    }

    //新项目和转让游标栏，用ViewPageIndicator出现bug，自己随便写个死的
    private void initOnChangeListener() {
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                if (position == 0) {
                    ll_blell_title1.setVisibility(View.VISIBLE);
                    ll_blell_title2.setVisibility(View.GONE);
                } else if (position == 1) {
                    ll_blell_title2.setVisibility(View.VISIBLE);
                    ll_blell_title1.setVisibility(View.GONE);
                }
            }
        });
    }

    public void initData() {
        ll_blell_title1.setVisibility(View.VISIBLE);
        ll_blell_title2.setVisibility(View.GONE);
        List<Fragment> fragmentList = getFragments();
        FragmentManager supportFragmentManager = getFragmentManager();
        mAdapter = new FragmentViewPagerAdapter(supportFragmentManager, mActivity,fragmentList);
        mViewPager.setAdapter(mAdapter);
        homeLoginRequest();
    }

    /**
     * banner展示
     */
    private void initBanner() {
        if (homeBean.isLogined()){
            top_qiandao.setVisibility(View.VISIBLE);
        }else {
            top_qiandao.setVisibility(View.GONE);
        }
        if (homeBean.isSigned()){
            top_qiandao_icon.setVisibility(View.VISIBLE);
        }else {
            top_qiandao_icon.setVisibility(View.GONE);
        }
        bannerList = homeBean.getBannerList();
        if (!(bannerList==null||bannerList.equals("null")||bannerList.size()<1)) {
            mViewFlow.setAdapter(new ImagePagerAdapter(mActivity, bannerList).setInfiniteLoop(true));
            mViewFlow.setmSideBuffer(bannerList.size()); // 实际图片张数
            if (bannerList.size()>1){
                mFlowIndicator.setVisibility(View.VISIBLE);
                mViewFlow.setFlowIndicator(mFlowIndicator);
                mViewFlow.setTimeSpan(3000);
                mViewFlow.setSelection(bannerList.size() * 1000); // 设置初始位置
                mViewFlow.startAutoFlowTimer();                   // 启动自动播放
            }
        }
    }
    private void initView(View view) {
        tv_title = (TextView) view.findViewById(R.id.top_title_tv);
        topbar_background = view.findViewById(R.id.view_color_change);
        topbar_background.setAlpha(0);                                  //设置初始透明度
        top_qiandao = (LinearLayout) view.findViewById(R.id.top_qiandao);
        top_qiandao_icon = (ImageView) view.findViewById(R.id.top_qiandao_icon);
        top_qiandao.setOnClickListener(this);

        mViewFlow = (ViewFlow) view.findViewById(R.id.viewflow);
        mFlowIndicator = (CircleFlowIndicator) view.findViewById(R.id.viewflowindic);

        //viewpage游标栏
        ll_blell_title1 = (LinearLayout) view.findViewById(R.id.ll_blell_title1);
        ll_blell_title2 = (LinearLayout) view.findViewById(R.id.ll_blell_title2);
        tv_anyone_transfer = (RelativeLayout) view.findViewById(R.id.tv_anyone_transfer);
        tv_my_newproject = (RelativeLayout) view.findViewById(R.id.tv_my_newproject);
        tv_anyone_transfer.setOnClickListener(this);
        tv_my_newproject.setOnClickListener(this);

        //自定义手势识别控件
        mainContainer = (ScrollableLinearLayout) view.findViewById(R.id.sc_container);
        mainContainer.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, getMainContainerHeight()));
        // 设置最大滚动距离
        mainContainer.setMaxScrollDistance(CommonUtils.dip2px(mActivity, ENTRANCE_GRIDVIEW_HEIGHT));
        mainContainer.setOnScrollListener(this);

        mViewPager = (ViewPager) view.findViewById(R.id.product_list_viewpager);
        hongbao = (ImageView) view.findViewById(R.id.hongbao);
        // 通过ImageView对象拿到背景显示的AnimationDrawable
        mAnimation = (AnimationDrawable) hongbao.getBackground();
        hongbao.setOnClickListener(this);
    }

    /**
     * 根据类别获取项目列表的fragment list
     *
     * @return fragment list
     */
    private List<Fragment> getFragments() {
        String[] types = this.getResources().getStringArray(R.array.product_list_types);
        List<Fragment> fragmentList = new ArrayList<>();
        for (String type : types) {
            ProductListFragment fragment = new ProductListFragment();//在这里面进行的
            Bundle bundle = new Bundle();
            bundle.putString("type", type);
            fragment.setArguments(bundle);
            fragmentList.add(fragment);
        }
        return fragmentList;
    }


    @Override
    public void onClick(View v) {
        if (!NewUtil.checkClick(v.getId())) return;
        User user = AccountManager.getInstance().getUser();
        switch (v.getId()) {
            case R.id.top_qiandao:
                /***  签到  网络请求  */
                dg = UIManager.getLoadingDialog(mActivity);
                dg.setCanceledOnTouchOutside(true);
                dg.show();
                if (user != null && user.getCurrUser().isLogged()) {
                    final Map<String, String> parameters = DataHandler.getParameters("1407");
                    parameters.put("id", user.getCurrUser().getSign());
                    JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon, error);
                    requen.add(request);
                }else {
                    startActivity(new Intent(mActivity, CheckMobileActivity.class));
                }
                break;

            case R.id.tv_anyone_transfer:
                mViewPager.setCurrentItem(1, true);
                break;
            case R.id.tv_my_newproject:
                mViewPager.setCurrentItem(0, true);
                break;
            case R.id.hongbao:
                String url;
                if (user != null && user.getCurrUser().isLogged()) {
                    url = DataHandler.WEBURL + "/front/wa/inviteNew?id="+ user.getCurrUser().getSign();
                }else {
                    url = DataHandler.WEBURL + "/front/wa/activityRules";
                }
                Bundle bundle = new Bundle();
                bundle.putString("url", url);
                Intent intent = new Intent(mActivity, YaoqingWeb.class);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    public void setIndeticViewPage(int index) {
        if (mViewPager != null) {
            mViewPager.setCurrentItem(index, true);
        }
    }

    /**
     * home  网络请求
     */
    private void homeLoginRequest() {
        final Map<String, String> parameters = DataHandler.getParameters("1402");
        User user = AccountManager.getInstance().getUser();
        if (user != null && user.getCurrUser().isLogged()) {
            parameters.put("id", user.getCurrUser().getSign());
        }
        parameters.put("currPage", "1");
        parameters.put("pageSize", "1");
        parameters.put("listType", "1");
        parameters.put("queryAcct", "");
        JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, homesucceedRespon, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                DataHandler.errorHandler(mActivity, error);
                if (SharedPreferencesUtils.getUserInfo(mActivity, "homeBean") != ""){
                    homeBean=JSON.parseObject(SharedPreferencesUtils.getUserInfo(mActivity, "homeBean"), HomeBean.class);
                    initBanner();
                }
            }
        });
        request.setRetryPolicy(new DefaultRetryPolicy(ConstantValues.TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requen.add(request);
    }

    private Response.ErrorListener error = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dg.dismiss();
            DataHandler.errorHandler(mActivity, error);
        }
    };

    private Response.Listener<JSONObject> homesucceedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.d("homeBean====="+jobj.toString());
            SharedPreferencesUtils.saveUserInfo(mActivity, "homeBean", jobj.toString());
            if (JSONManager.getError(jobj) == -1) {
                homeBean = JSON.parseObject(jobj.toString(), HomeBean.class);
                initBanner();
                hongbaologo();
            }
        }
    };

    /**
     * 红包活动悬浮层
     */
    private void hongbaologo(){
        if (homeBean.getSuspend() == 0){
            hongbao.setVisibility(View.GONE);
        }else {
            hongbao.setVisibility(View.VISIBLE);
            // 为了防止在onCreate方法中只显示第一帧的解决方案之一
            hongbao.post(new Runnable() {
                @Override
                public void run() {
                    mAnimation.start();
                }
            });
            /**延时2秒*/
            new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    mAnimation.stop();
                    return true;
                }
            }).sendEmptyMessageDelayed(0, 2000);
        }
    }

    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.d("签到 ==========" + jobj);
            dg.dismiss();
            int code = 0;
            double income = 0;
            try {
                code = (int) jobj.get("code");
                income = (double) jobj.get("income");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (code == -1 ||code == -4 || code == -5) {
                Intent intent = new Intent(mActivity, QianDaoAct.class);
                Bundle bundle = new Bundle();
                bundle.putDouble("income", income);
                bundle.putInt("code", code);
                intent.putExtras(bundle);
                startActivity(intent);
            } else if (code == -2) {
                ToastManager.showShort(mActivity, "登录超时,请重新登录");
            }
        }
    };

    /**
     * 获取ScrollableLinearLayout的高度
     * 其高度等于屏幕高度 - 状态栏高度 - TabHost高度
     *
     * @return height
     */
    private int getMainContainerHeight() {
        return CommonUtils.getScreenHeight(mActivity) - CommonUtils.getStatusBarHeight(mActivity);
    }


    @Override
    public String getFragmentName() {
        return TAG;
    }

    @Override
    public boolean canScrollUp() {
        return mainContainer.getScrollY() < mainContainer.getMaxScrollDistance();
    }

    @Override
    public boolean canScrollDown() {
        int scrollY = mainContainer.getScrollY();
        boolean canScrollDown = scrollY > 0 && scrollY < mainContainer.getMaxScrollDistance();
        int index = mViewPager.getCurrentItem();
        if (index >= 0) {
            //Fragment fragment = mAdapter.getItem(index);滑动不下来的尝试解决方案,是否有效,需要长时间观察
            Fragment fragment = (Fragment) mAdapter.instantiateItem(mViewPager, index);
            if (fragment instanceof ProductListFragment) {
                ProductListFragment commonFragment = (ProductListFragment) fragment;
                ListView listView = commonFragment.getListView();
                if (listView != null && listView.getFirstVisiblePosition() == 0 && listView.getChildAt(0) != null
                        && listView.getChildAt(0).getTop() == listView.getPaddingTop()) {
                    canScrollDown = true;
                }
                if (listView == null) {  //解决有时候不能下滑看到banner图的问题, 权宜之计.
                    canScrollDown = true;
                }
            }
        }
        return canScrollDown;
    }

    @Override
    public ListView getListView() {
        int index = mViewPager.getCurrentItem();
        if (index >= 0) {
            //Fragment fragment = mAdapter.getItem(index);滑动不下来的尝试解决方案,是否有效,需要长时间观察
            Fragment fragment = (Fragment) mAdapter.instantiateItem(mViewPager, index);
            if (fragment instanceof ProductListFragment) {
                ProductListFragment commonFragment = (ProductListFragment) fragment;
                return commonFragment.getListView();
            }
        }
        return null;
    }

    @Override
    public ViewPager getViewPager() {
        return mViewPager;
    }

    @Override
    public void onScrollChanged(int scrollY) {
        topbar_background.setAlpha((float) scrollY / ENTRANCE_GRIDVIEW_HEIGHT);
        if (scrollY>0){
            top_qiandao.getBackground().setAlpha(ENTRANCE_GRIDVIEW_HEIGHT/scrollY);
            tv_title.setText("P兜理财");
        }else {
            top_qiandao.getBackground().setAlpha(255);
            tv_title.setText("");
        }
    }

}
